<template>
  <div class="performance-appraisals section-container">
    <div class="page-header">
      <h2 class="page-title">绩效考核管理</h2>
      <p class="page-subtitle">查看、评估和管理员工的绩效考核数据，提升组织绩效管理水平</p>
    </div>
    
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="员工ID">
          <el-input v-model="searchForm.employeeId" placeholder="输入员工ID" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="考核等级">
          <el-select v-model="searchForm.grade" placeholder="选择考核等级" clearable class="custom-select">
            <el-option label="A-优秀" value="A"></el-option>
            <el-option label="B-良好" value="B"></el-option>
            <el-option label="C-合格" value="C"></el-option>
            <el-option label="D-需改进" value="D"></el-option>
            <el-option label="E-不合格" value="E"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadPerformanceAppraisals" class="search-btn">查询</el-button>
          <el-button @click="resetSearch" class="reset-btn">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="openAddDialog" class="action-btn">
        <i class="el-icon-plus"></i> 新增考核记录
      </el-button>
      <el-button type="success" @click="exportToExcel" class="action-btn">
        <i class="el-icon-download"></i> 导出Excel
      </el-button>
    </div>
    
    <!-- 数据表格 -->
    <el-card class="data-card">
      <el-table 
        :data="performanceAppraisals" 
        border 
        stripe 
        style="width: 100%" 
        v-loading="loading"
        class="custom-table"
        :header-cell-style="{ background: '#f5f5f7', color: '#1d1d1f', fontWeight: '500' }"
      >
        <el-table-column prop="id" label="考核ID" width="80" align="center"></el-table-column>
        <el-table-column prop="employeeId" label="员工ID" width="100" align="center"></el-table-column>
        <el-table-column label="考核周期" width="220" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.periodStart) }} 至 {{ formatDate(scope.row.periodEnd) }}
          </template>
        </el-table-column>
        <el-table-column prop="content" label="考核内容" show-overflow-tooltip></el-table-column>
        <el-table-column prop="score" label="考核得分" width="100" align="center">
          <template #default="scope">
            <span class="score-value">{{ scope.row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="考核等级" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getGradeTagType(scope.row.grade)" class="grade-tag">{{ scope.row.grade }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="evaluatorId" label="评价人ID" width="100" align="center"></el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="viewDetail(scope.row)" class="detail-btn">详情</el-button>
              <el-button size="small" type="primary" @click="openEditDialog(scope.row)" class="edit-btn">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.id)" class="delete-btn">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="custom-pagination"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增考核记录' : '编辑考核记录'"
      v-model="dialogVisible"
      width="650px"
      custom-class="custom-dialog"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" class="custom-form">
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model.number="form.employeeId" placeholder="请输入员工ID" class="custom-input"></el-input>
        </el-form-item>
        <el-form-item label="考核周期" prop="period">
          <el-date-picker
            v-model="form.period"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="custom-date-picker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="考核内容" prop="content">
          <el-input type="textarea" v-model="form.content" placeholder="请输入考核内容" rows="3" class="custom-textarea"></el-input>
        </el-form-item>
        <el-form-item label="考核指标" prop="indicators">
          <el-input type="textarea" v-model="form.indicators" placeholder="请输入考核指标，JSON格式" class="custom-textarea"></el-input>
          <div class="form-tip">例如：{"完成率":90,"质量评分":85,"团队贡献":88}</div>
        </el-form-item>
        <el-form-item label="考核得分" prop="score">
          <el-input-number v-model="form.score" :min="0" :max="100" :precision="2" placeholder="请输入考核得分" class="custom-input-number"></el-input-number>
        </el-form-item>
        <el-form-item label="考核等级" prop="grade">
          <el-select v-model="form.grade" placeholder="请选择考核等级" class="custom-select">
            <el-option label="A-优秀" value="A"></el-option>
            <el-option label="B-良好" value="B"></el-option>
            <el-option label="C-合格" value="C"></el-option>
            <el-option label="D-需改进" value="D"></el-option>
            <el-option label="E-不合格" value="E"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核评语" prop="comment">
          <el-input type="textarea" v-model="form.comment" placeholder="请输入考核评语" class="custom-textarea"></el-input>
        </el-form-item>
        <el-form-item label="评价人ID" prop="evaluatorId">
          <el-input v-model.number="form.evaluatorId" placeholder="请输入评价人ID" class="custom-input"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitForm" class="confirm-btn">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 详情对话框 -->
    <el-dialog
      title="考核详情"
      v-model="detailDialogVisible"
      width="700px"
      custom-class="custom-dialog"
    >
      <el-descriptions :column="2" border class="custom-descriptions">
        <el-descriptions-item label="考核ID">{{ detail.id }}</el-descriptions-item>
        <el-descriptions-item label="员工ID">{{ detail.employeeId }}</el-descriptions-item>
        <el-descriptions-item label="考核开始日期">{{ formatDate(detail.periodStart) }}</el-descriptions-item>
        <el-descriptions-item label="考核结束日期">{{ formatDate(detail.periodEnd) }}</el-descriptions-item>
        <el-descriptions-item label="考核内容" :span="2">{{ detail.content }}</el-descriptions-item>
        <el-descriptions-item label="考核指标" :span="2">
          <pre class="json-display">{{ formatJSON(detail.indicators) }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="考核得分">{{ detail.score }}</el-descriptions-item>
        <el-descriptions-item label="考核等级">
          <el-tag :type="getGradeTagType(detail.grade)" class="grade-tag">{{ detail.grade }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="考核评语" :span="2">{{ detail.comment }}</el-descriptions-item>
        <el-descriptions-item label="评价人ID">{{ detail.evaluatorId }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false" class="close-btn">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  ElMessageBox,
  ElMessage,
  ElLoading
} from 'element-plus'
import request from '../utils/request'

export default {
  name: 'PerformanceAppraisals',
  setup() {
    // 数据列表
    const performanceAppraisals = ref([])
    const loading = ref(false)
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    // 搜索表单
    const searchForm = reactive({
      employeeId: '',
      grade: ''
    })
    
    // 表单数据
    const formRef = ref(null)
    const form = reactive({
      id: null,
      employeeId: '',
      period: [],
      content: '',
      indicators: '',
      score: null,
      grade: '',
      comment: '',
      evaluatorId: ''
    })
    
    // 详情数据
    const detail = reactive({
      id: null,
      employeeId: '',
      periodStart: '',
      periodEnd: '',
      content: '',
      indicators: '',
      score: null,
      grade: '',
      comment: '',
      evaluatorId: '',
      createTime: ''
    })
    
    // 对话框控制
    const dialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const dialogType = ref('add') // 'add' 或 'edit'
    
    // 表单验证规则
    const rules = {
      employeeId: [
        { required: true, message: '请输入员工ID', trigger: 'blur' },
        { type: 'number', message: '员工ID必须为数字', trigger: 'blur' }
      ],
      period: [
        { required: true, message: '请选择考核周期', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入考核内容', trigger: 'blur' }
      ],
      indicators: [
        { required: true, message: '请输入考核指标', trigger: 'blur' }
      ],
      grade: [
        { required: true, message: '请选择考核等级', trigger: 'change' }
      ],
      evaluatorId: [
        { required: true, message: '请输入评价人ID', trigger: 'blur' },
        { type: 'number', message: '评价人ID必须为数字', trigger: 'blur' }
      ]
    }
    
    // 加载绩效考核列表
    const loadPerformanceAppraisals = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: currentPage.value,
          pageSize: pageSize.value
        }
        
        if (searchForm.employeeId) {
          params.employeeId = searchForm.employeeId
        }
        
        if (searchForm.grade) {
          params.grade = searchForm.grade
        }
        
        console.log('Sending request to fetch performance appraisals with params:', params)
        const res = await request.get('/api/performances', { params })
        console.log('Performance appraisals response:', res)
        
        // 后端返回成功状态码为200
        if (res.code === 200) {
          // 检查数据格式是否正确
          if (res.data && Array.isArray(res.data.records)) {
            console.log('Records received:', res.data.records.length)
            performanceAppraisals.value = res.data.records
            total.value = res.data.total || 0
          } else if (Array.isArray(res.data)) {
            // 如果后端直接返回数组而非分页对象
            console.log('Array data received:', res.data.length)
            performanceAppraisals.value = res.data
            total.value = res.data.length
          } else {
            console.error('Unexpected data format:', res.data)
            performanceAppraisals.value = []
            total.value = 0
            ElMessage.warning('数据格式异常')
          }
        } else {
          console.error('API error:', res.msg)
          performanceAppraisals.value = []
          total.value = 0
          ElMessage.error(res.msg || '加载绩效考核失败')
        }
      } catch (error) {
        console.error('加载绩效考核失败:', error)
        performanceAppraisals.value = []
        total.value = 0
        ElMessage.error('加载绩效考核失败')
      } finally {
        loading.value = false
      }
    }
    
    // 重置搜索条件
    const resetSearch = () => {
      searchForm.employeeId = ''
      searchForm.grade = ''
      loadPerformanceAppraisals()
    }
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return ''
      return dateStr
    }
    
    // 格式化JSON
    const formatJSON = (jsonStr) => {
      if (!jsonStr) return ''
      try {
        const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr
        return JSON.stringify(obj, null, 2)
      } catch (e) {
        return jsonStr
      }
    }
    
    // 获取等级标签类型
    const getGradeTagType = (grade) => {
      const typeMap = {
        'A': 'success',
        'B': 'info',
        'C': 'warning',
        'D': 'danger',
        'E': 'danger'
      }
      return typeMap[grade] || 'info'
    }
    
    // 打开添加对话框
    const openAddDialog = () => {
      dialogType.value = 'add'
      form.id = null
      form.employeeId = ''
      form.period = []
      form.content = ''
      form.indicators = ''
      form.score = null
      form.grade = ''
      form.comment = ''
      form.evaluatorId = ''
      dialogVisible.value = true
    }
    
    // 打开编辑对话框
    const openEditDialog = (row) => {
      dialogType.value = 'edit'
      form.id = row.id
      form.employeeId = row.employeeId
      form.period = [row.periodStart, row.periodEnd]
      form.content = row.content
      form.indicators = row.indicators
      form.score = row.score
      form.grade = row.grade
      form.comment = row.comment
      form.evaluatorId = row.evaluatorId
      dialogVisible.value = true
    }
    
    // 查看详情
    const viewDetail = async (row) => {
      try {
        const res = await request.get(`/api/performances/${row.id}`)
        if (res.code === 200) {
          Object.assign(detail, res.data)
          detailDialogVisible.value = true
        } else {
          ElMessage.error(res.msg || '获取详情失败')
        }
      } catch (error) {
        console.error('获取详情失败:', error)
        ElMessage.error('获取详情失败')
      }
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            let res
            const data = {
              ...form,
              periodStart: form.period[0],
              periodEnd: form.period[1]
            }
            delete data.period
            
            if (dialogType.value === 'add') {
              res = await request.post('/api/performances', data)
            } else {
              res = await request.put(`/api/performances/${form.id}`, data)
            }
            
            if (res.code === 200) {
              ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
              dialogVisible.value = false
              loadPerformanceAppraisals()
            } else {
              ElMessage.error(res.msg || (dialogType.value === 'add' ? '添加失败' : '修改失败'))
            }
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加失败:' : '修改失败:', error)
            ElMessage.error(dialogType.value === 'add' ? '添加失败' : '修改失败')
          }
        }
      })
    }
    
    // 删除考核记录
    const handleDelete = (id) => {
      ElMessageBox.confirm('确认删除该考核记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await request.delete(`/api/performances/${id}`)
          if (res.code === 200) {
            ElMessage.success('删除成功')
            loadPerformanceAppraisals()
          } else {
            ElMessage.error(res.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {})
    }
    
    // 导出Excel
    const exportToExcel = () => {
      // 构建导出URL
      let exportUrl = `${request.defaults.baseURL}/api/performances/export?`
      
      // 添加筛选条件
      if (searchForm.employeeId) {
        exportUrl += `employeeId=${searchForm.employeeId}&`
      }
      
      if (searchForm.grade) {
        exportUrl += `grade=${searchForm.grade}&`
      }
      
      // 触发下载
      ElMessageBox.confirm('确认导出当前筛选条件下的考核数据?', '导出确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        // 显示加载中
        const loading = ElLoading.service({
          lock: true,
          text: '正在导出数据，请稍候...',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        // 创建隐藏的a标签进行下载
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = exportUrl
        link.setAttribute('download', `绩效考核数据_${new Date().getTime()}.xlsx`)
        document.body.appendChild(link)
        
        // 模拟点击下载
        link.click()
        
        // 下载后移除临时元素
        setTimeout(() => {
          document.body.removeChild(link)
          loading.close()
          ElMessage.success('数据导出成功')
        }, 2000)
      }).catch(() => {
        // 用户取消导出
      })
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadPerformanceAppraisals()
    }
    
    const handleCurrentChange = (page) => {
      currentPage.value = page
      loadPerformanceAppraisals()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadPerformanceAppraisals()
    })
    
    return {
      performanceAppraisals,
      loading,
      currentPage,
      pageSize,
      total,
      searchForm,
      formRef,
      form,
      detail,
      dialogVisible,
      detailDialogVisible,
      dialogType,
      rules,
      loadPerformanceAppraisals,
      resetSearch,
      formatDate,
      formatJSON,
      getGradeTagType,
      openAddDialog,
      openEditDialog,
      viewDetail,
      submitForm,
      handleDelete,
      exportToExcel,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.performance-appraisals {
  padding: 0 24px;
}

.page-header {
  margin-bottom: 32px;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 12px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.search-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.07);
}

.search-form {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.data-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s;
}

.data-card:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.08);
}

.custom-table {
  margin-bottom: 20px;
}

.custom-input, .custom-select, .custom-textarea, .custom-input-number {
  width: 100%;
  border-radius: 8px;
}

.custom-date-picker {
  width: 100%;
}

.score-value {
  font-weight: 500;
  color: var(--el-color-primary);
}

.grade-tag {
  font-weight: 500;
  border-radius: 10px;
  padding: 2px 8px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.detail-btn, .edit-btn, .delete-btn {
  padding: 6px 12px;
  border-radius: 12px;
}

.pagination-container {
  padding: 16px 0;
  display: flex;
  justify-content: center;
}

.custom-pagination {
  margin-top: 16px;
}

.custom-form .el-form-item {
  margin-bottom: 20px;
}

.form-tip {
  font-size: 12px;
  color: var(--app-secondary-text);
  margin-top: 5px;
}

.custom-dialog .el-dialog__header {
  padding: 24px;
  text-align: center;
}

.custom-dialog .el-dialog__body {
  padding: 0 24px 24px;
}

.custom-dialog .el-dialog__footer {
  padding: 16px 24px 24px;
  text-align: center;
}

.json-display {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 8px;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 200px;
  overflow-y: auto;
  margin: 0;
  font-family: "SF Mono", Monaco, "Andale Mono", "Lucida Console", monospace;
  font-size: 13px;
}

.custom-descriptions :deep(.el-descriptions__header) {
  margin-bottom: 16px;
}

.custom-descriptions :deep(.el-descriptions__title) {
  font-weight: 500;
  font-size: 16px;
}

.custom-descriptions :deep(.el-descriptions__label) {
  font-weight: 500;
  color: var(--app-text-color);
  background-color: #f5f7fa;
}

.custom-descriptions :deep(.el-descriptions__content) {
  line-height: 1.6;
}

.cancel-btn, .close-btn {
  min-width: 90px;
  border-radius: 18px;
}

.confirm-btn {
  min-width: 90px;
  border-radius: 18px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .action-bar {
    flex-wrap: wrap;
  }
  
  .action-btn {
    flex: 1;
    min-width: 0;
  }
  
  .custom-descriptions :deep(.el-descriptions-item__label) {
    width: 120px;
  }
}
</style> 